package com.tcpengine.server;

import com.tcpengine.handler.GameProcess;
import com.tcpengine.handler.WsHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class WsService implements Runnable {
	
	GameProcess m_gameProcess = null;
	public WsService(GameProcess gameProcess) {
		m_gameProcess = gameProcess;
	}

	@Override
	public void run() {
		EventLoopGroup webBossGroup = new NioEventLoopGroup(1);
    	EventLoopGroup webWorkGroup = new NioEventLoopGroup();
    	ChannelFuture webFuture = null;
        try{
        	ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(webBossGroup,webWorkGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                        	ChannelPipeline pipeline = socketChannel.pipeline();
                        	pipeline.addLast(new HttpServerCodec()); // http 编码
                            pipeline.addLast(new HttpObjectAggregator(65536)); // http 消息聚合器
                            pipeline.addLast(new WebSocketServerProtocolHandler("/", null, true)); // 协议
                            pipeline.addLast(new WsHandler(m_gameProcess)); // 处理WebSocketFrame

                        }
                    });
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.option(ChannelOption.SO_REUSEADDR, true);
			bootstrap.option(ChannelOption.SO_SNDBUF, 1024);
			bootstrap.option(ChannelOption.SO_RCVBUF, 1024);
           
            try {
            	 System.out.println("开启 websocket 协议端口是 8888");
				webFuture = bootstrap.bind(8888).sync();
				webFuture.channel().closeFuture().sync();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            
        }finally {
            webBossGroup.shutdownGracefully();
            webWorkGroup.shutdownGracefully();
            System.out.println("关闭websocket 协议端口是 8888");
        }
	}

}
